package com.ynding;

import java.awt.*;
/**
 * <p> 旋转的图形</p>
 *
 * @author ynding
 * @version 2021/4/14
 **/
public class Rotator extends java.applet.Applet implements Runnable {
    int   frameWidth, frameHeight;//每一帧的宽和高
    int   nColumns = 1;//横向的帧数
    int   nRows = 1;//纵向的帧数
    int   nFrames = 1;//帧数
    int   delay = 167;  //毫秒(6帧/秒)
    int   frame = 0;
    boolean suspended = false;
    Thread  spinThread ;//定义动画线程
    Image   spinImage;
    //初始化，获取参数
    @Override
    public void init() {
        String param = getParameter("width");
        if (param != null) {
            frameWidth = Integer.parseInt(param);
        }
        param = getParameter("height");
        if (param != null) {
            frameHeight = Integer.parseInt(param);
        }
        param = getParameter("frames");
        if (param != null) {
            nFrames = Integer.parseInt(param);
        }
        param = getParameter("rate");
        if (param != null) {
            delay =1000 / Integer.parseInt(param);
        }
        param = getParameter("columns");
        if (param != null) {
            nColumns = Integer.parseInt(param);
        }
        param = getParameter("rows");
        if (param != null) {
            nRows = Integer.parseInt(param);
        }
        if (delay < 10) {
            delay = 10;
        }
        if (nFrames == 1) {
            nFrames = nColumns * nRows;
        }
        if (nColumns == 1 && nRows == 1) {
            nColumns = nFrames;
        }
        spinImage = getImage(getCodeBase(), getParameter("image"));
    }
    //run()方法，负责播放图片，由线程调用
    public void run() {
        while (spinThread != null) {
            repaint() ;
            try {
                spinThread.sleep(delay);
            }
            catch (InterruptedException e) { }
        }
    }
    //update()方法，调用paint()方法
    @Override
    public void update(Graphics g) {
        paint(g);
    }
    //paint()方法，负责在屏幕上绘制图像
    @Override
    public void paint(Graphics g) {
        //画当前帧，使用负数坐标以便在画图时剪切帧
        g.drawImage ( spinImage,
                -frameWidth * (frame % nColumns),
                -frameHeight * ((frame / nColumns) % nRows),
                this );
        //检查绘制的图像是否是最后一幅，然后返回第一幅
        if (++frame  == nFrames) {
            frame = 0;
        }
    }
    //处理鼠标事件
    @Override
    public boolean mouseDown(Event evt, int x, int y) {
        if (suspended) {
            spinThread.resume();
        } else {
            spinThread.suspend();
        }
        suspended = !suspended;
        return true;
    }
    //启动线程
    @Override
    public void start() {
        if (spinThread == null) {
            spinThread = new Thread (this, "Spin");
            spinThread.start();
        }
    }
    //停止线程
    @Override
    public void stop() {
        spinThread.stop();
        spinThread = null;
    }
}
